import express from "express";
import cors from "cors";
import multer from "multer";
import fs from "node:fs";
import path from "node:path";
//1.初始化multer
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads/"); //每个切片存放的目录
  },
  filename: (req, file, cb) => {
    cb(null, `${req.body.index}-${req.body.filename}`); //文件名称
  },
});
const upload = multer({ storage });
const app = express();
app.use(cors());
app.use(express.json());
//upload.single upload.array
app.post("/upload", upload.single("file"), (req, res) => {
  //   console.log(req.body);
  res.send("ok");
});
app.post("/merge", (req, res) => {
  //1.读取目录下所有切片 process.cwd()=根目录
  const uploadDir = path.join(process.cwd(), "uploads");
  const dirs = fs.readdirSync(uploadDir);
  //排序
  dirs.sort((a, b) => a.split("-")[0] - b.split("-")[0]);
  const filePath = path.join(
    process.cwd(),
    "video",
    `${req.body.filename}.mp4`
  );
  dirs.forEach((item) => {
    console.log("filePath: ", filePath);
    fs.appendFileSync(filePath, fs.readFileSync(`${uploadDir}/${item}`));
    fs.unlinkSync(`${uploadDir}/${item}`);
  });
  console.log("dirs: ", dirs);
});
app.listen(3000, () => {
  console.log("http://localhost:3000");
});
